package cn.fl.capital.service.impl;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.mid.core.framework.page.Pager;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.cmm.cache.framework.utils.PropertiesCacheUtils;
import cn.fl.capital.condition.CapClaimDtlQC;
import cn.fl.capital.constant.CapClaimInfoConstant;
import cn.fl.capital.dto.CapClaimDtlDTO;
import cn.fl.capital.dto.CapPayInfoDTO;
import cn.fl.capital.service.ICapClaimDtlApiService;
import cn.fl.capital.service.ICapClaimDtlService;
import cn.fl.capital.service.ICapPayInfoApiService;
import cn.fl.capital.transform.CapClaimDtlVOTransform;
import cn.fl.capital.vo.CapClaimDtlVO;
import cn.fl.framework.base.context.CurrentThreadContext;

import com.lionbridge.activiti.WorkflowClient;
import com.lionbridge.activiti.dto.MessageDTO;
import com.lionbridge.activiti.dto.TaskDTO;

import fl.flow.facade.flow.constant.FlowConstant;


/**
 * @Description: 赔付款拆分记录表 客户端服务层接口实现
 * @Description: 业务层方法名称前缀：新增：add* 删除：remove* 修改：modify* 查询对象：select* get* 批量：batch* 查询集合：search*
 */
@Service
public class CapClaimDtlServiceImpl implements ICapClaimDtlService {

	/**
	 * 日志
	 */
	private static final Logger logger = LoggerFactory.getLogger(CapClaimDtlServiceImpl.class);
	
	/**
	 * 自定义 API 自行注入需要的API服务
	 */
	@Autowired
	private ICapClaimDtlApiService capClaimDtlApiService;
	/**
     * 数据字典服务
     */
	@Autowired
    private ISysDictionaryApiService sysDictionaryApiService;
	@Autowired
	private ICapPayInfoApiService capPayInfoApiService;

	@Override
	public CapClaimDtlVO selectById(Long id) throws BaseException{
		if(StringUtils.isEmpty(id)){
			BaseLogUtils.info(logger, "selectById", "主键参数不能为空!", CurrentThreadContext.getCurrentUserName());
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "获取对象主键不能为空!");
		}
		CapClaimDtlDTO dto = this.capClaimDtlApiService.selectCapClaimDtlById(id);
		return CapClaimDtlVOTransform.toVO(dto);
	}

	@Override
	public Long add(CapClaimDtlVO entity) throws BaseException{
		if(null == entity){
			BaseLogUtils.info(logger, "add", "新增对象不存在!");
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600,"新增对象不存在!");
		};
		return this.capClaimDtlApiService.addCapClaimDtl(CapClaimDtlVOTransform.toDTO(entity));
	}

	@Override
	public boolean removeById(Long id) throws BaseException{
		if(StringUtils.isEmpty(id)){
			BaseLogUtils.info(logger, "removeById", "删除对象主键不能为空!");
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600,"删除对象主键不能为空!");
		};
		return this.capClaimDtlApiService.removeCapClaimDtlById(id);
	}
	
	/**
     * 删除
     * @param ids
     * @return
     */
    public boolean removeByIds(List<Long> ids)throws BaseException{
		if(CollectionUtils.isEmpty(ids)){
			BaseLogUtils.info(logger, "removeByIds", "删除主键参数集合不能为空!", CurrentThreadContext.getCurrentUserName());
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600,"删除对象主键不能为空!");
		};
		return false;
    }

	@Override
	public boolean modify(CapClaimDtlVO entity) throws BaseException{
		if(null == entity){
			BaseLogUtils.info(logger, "modify", "修改对象不能为空!");
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600,"修改对象不能为空!");
		};
		return this.capClaimDtlApiService.modifyCapClaimDtl(CapClaimDtlVOTransform.toDTO(entity));
	}

	@Override
	public Pager searchListPage(Pager page) throws BaseException{
		if(null == page){
			page = new Pager();
		}
		return this.capClaimDtlApiService.searchCapClaimDtlListPage(page);
	}

	@Override
	public List<CapClaimDtlVO> searchList(CapClaimDtlQC condition)
			throws BaseException {
		return CapClaimDtlVOTransform.toVOList(this.capClaimDtlApiService.searchCapClaimDtlList(condition));
	}

	@Override
	public List<CapClaimDtlVO> searchCapClaimDtlListByFlow(
			String processInstanceId,Long claimId,Long payId) throws BaseException {
		CapClaimDtlQC qc=new CapClaimDtlQC();
		List<CapClaimDtlVO> capClaimDtlVOList = null;
        qc.setClaId(Long.valueOf(claimId));
        qc.setSortName("CRT_TM");
        qc.setSortOrder("ASC");
        capClaimDtlVOList = this.searchList(qc);
        if(CollectionUtils.isNotEmpty(capClaimDtlVOList)){
        	for(CapClaimDtlVO vo:capClaimDtlVOList){
        		DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    	        String tsStr = sdf.format(vo.getCrtTm());
    	        vo.setTaskTMStr(tsStr);
        	}
        	return capClaimDtlVOList;
        }else{
        	WorkflowClient.setBasePath(PropertiesCacheUtils.getProperty(FlowConstant.FLOW_FLOW_PROPERTIES_FLOW_BASE_URL));
            MessageDTO<TaskDTO> messageDTO = WorkflowClient.processHistoryList(processInstanceId);
        	List<TaskDTO> taskDTOList = messageDTO.getDatas();
        	if(CollectionUtils.isNotEmpty(taskDTOList)){
        		capClaimDtlVOList = new ArrayList<CapClaimDtlVO>();
        		Map<String, String> claFlowCdMap = this.sysDictionaryApiService.searchGroupToMap(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), CapClaimInfoConstant.CAP_CLA_PAY_FLOW_GRP_CD);
        		CapPayInfoDTO payInfoDTO = this.capPayInfoApiService.selectCapPayInfoById(payId);
        		for(TaskDTO taskDTO:taskDTOList){
        			if(claFlowCdMap!=null){
        				if(taskDTO.getActivityType().equals("startEvent")){
        					CapClaimDtlVO vo = new CapClaimDtlVO();
                			vo.setClaId(claimId);
                			vo.setTaskDefKey(taskDTO.getTaskDefKey());
                			vo.setTaskDefNm("开始计时");
                			vo.setOptUsrId(taskDTO.getAssignee());
                			vo.setTaskTakeMs(0L);
                	        DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                	        String tsStr = sdf.format(payInfoDTO.getApplyDt());
                	        vo.setTaskTMStr(tsStr);
                			vo.setCrtTm(payInfoDTO.getApplyDt());
                			vo.setIsDel(0);
                			capClaimDtlVOList.add(vo);
            			}else if(claFlowCdMap.containsKey(taskDTO.getTaskDefKey())){
            				CapClaimDtlVO vo = new CapClaimDtlVO();
                			vo.setClaId(claimId);
                			vo.setTaskDefKey(taskDTO.getTaskDefKey());
                			vo.setTaskDefNm(taskDTO.getName()==null?taskDTO.getOutgoingFlow():(taskDTO.getName()+"("+taskDTO.getOutgoingFlow()+")"));
                			vo.setOptUsrId(taskDTO.getAssignee());
                			vo.setTaskTakeMs((taskDTO.getEndTime().getTime()-taskDTO.getStartTime().getTime()));
                	        DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                	        String tsStr = sdf.format(taskDTO.getEndTime());
                	        vo.setTaskTMStr(tsStr);
                			vo.setCrtTm(taskDTO.getEndTime());
                			vo.setIsDel(0);
                			capClaimDtlVOList.add(vo);
            			} 
        			}      			   			
        		}
        		capClaimDtlVOList = mergeSameTask(capClaimDtlVOList);
        	}
    		return capClaimDtlVOList;
        }	
	}
	/**
	 * 处理重复节点
	 * @param capClaimDtlVOList
	 * @return
	 */
	private List<CapClaimDtlVO> mergeSameTask(List<CapClaimDtlVO> capClaimDtlVOList){
		List<CapClaimDtlVO> newCapClaimDtlVOList=new ArrayList<>(capClaimDtlVOList.size());
		Map<String, CapClaimDtlVO> capMap = new LinkedHashMap<String, CapClaimDtlVO>(capClaimDtlVOList.size());
		for(CapClaimDtlVO vo:capClaimDtlVOList){
			if(capMap!=null){
				if(capMap.containsKey(vo.getTaskDefKey())){
					CapClaimDtlVO mapVo=capMap.get(vo.getTaskDefKey());
					vo.setTaskTakeMs(mapVo.getTaskTakeMs()+vo.getTaskTakeMs());
					capMap.remove(vo.getTaskDefKey());
					capMap.put(vo.getTaskDefKey(), vo);
				}else{
					capMap.put(vo.getTaskDefKey(), vo);
				}			
			}
		}
		for(Entry<String, CapClaimDtlVO> capEntry: capMap.entrySet()){
			newCapClaimDtlVOList.add(capEntry.getValue());
		}
		return newCapClaimDtlVOList;
	}
}
